<template>
  <div>
    <div class="operate">
      <el-button link type="primary" @click="operateRow('add')" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: #ff9900;
            color: rgba(255, 255, 255, 1);
          ">新增</el-button>
      <!-- <el-button link type="primary" @click="importbtn" class="btnhover" style="
          width: 90px;
          height: 30px;
          background-color: #ff9900;
          color: rgba(255, 255, 255, 1);margin-right: 12px;
        ">批量导入</el-button>
      <PartyImportForm ref="importFormRef" @success="getLeaderManae" />
      <el-button link type="primary" @click="downloadbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: #ff9900;
            color: rgba(255, 255, 255, 1);
          ">模板下载</el-button> -->
      <el-button link type="primary" @click="exportbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: #ff9900;
            color: rgba(255, 255, 255, 1);
          ">批量导出</el-button>
      <el-button link type="primary" @click="alldelbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: #ff9900;
            color: rgba(255, 255, 255, 1);
          ">批量删除</el-button>
      <el-form @submit.prevent="getLeaderManage">
        <el-form-item label="姓名" style="margin-right: 15px;margin-left: 13px;">
          <el-input v-model="name" placeholder="" @keyup.enter="getLeaderManage" style="width: 200px" />
        </el-form-item>
      </el-form>
      <el-button @click="getLeaderManage" class="btn btnsearch">查询</el-button>
      <el-button @click="handleReset" class="btn btnreset">重置</el-button>
    </div>
    <div class="mt-0 content">
      <div class="left">
        <div class="flex pd-16">
          <span>党组织架构</span>
        </div>
        <el-tree ref="tree" node-key="id" :data="treeData" :props="defaultProps" default-expand-all
          @node-click="handleNodeClick">
          <template #default="{ node }">
            <span class="custom-tree-node">
              <span v-html="node.label.length > 8 ? node.label.slice(0, 8) + '...' : node.label"
                :title="node.label"></span>
            </span>
          </template>
        </el-tree>
      </div>
      <div class="right">
        <el-table v-loading="loading" element-loading-text="Loading..." :data="tableData"
          :header-cell-style="headerCellStyle" @selection-change="handleSelectionChange" height="calc(100vh - 260px)"
          style="width: 100%" row-key="id" default-expand-all>
          <el-table-column type="selection" width="50" />
          <el-table-column prop="name" label="姓名" min-width="140" align="center" show-overflow-tooltip>
            <template #default="scope">
              <div class="namecont">
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="memberType" label="党员类型" align="center" min-width="200">
            <template #default="{ row }">
              {{ typeRelate(row.memberType) }}
            </template>
          </el-table-column>
          <el-table-column prop="sex" label="性别" align="center" min-width="120">
            <template #default="{ row }">
              {{ sexTypeObj[row.sex] }}
            </template>
          </el-table-column>
          <el-table-column prop="telephone" label="联系电话" align="center" min-width="200">
            <template #default="{ row }">
              {{ row.telephone === null ? '--' : row.telephone }}
            </template>
          </el-table-column>
          <el-table-column prop="title" label="党内职务" align="center" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="namecont">
                {{ row.title === null ? '--' : row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column :formatter="dateFormatter2" align="center" label="转为预备党员日期" prop="unofficialMemberTime"
            min-width="200">
            <template #default="{ row }">
              {{ row.unofficialMemberTime === null ? '--' : row.unofficialMemberTime }}
            </template>
          </el-table-column>
          <el-table-column :formatter="dateFormatter2" align="center" label="转为正式党员日期" prop="officialMemberTime"
            min-width="200" />
          <el-table-column label="操作" fixed="right" width="200" align="center">
            <template #default="{ row }">
              <el-button link type="primary" @click="detailsbtn(row)">详情</el-button>
              <el-button type="primary" link @click="operateRow('edit', row)">编辑</el-button>
              <el-button type="primary" link @click="operateRow('del', row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex mt-16">
          <el-pagination class="ml-auto" :hide-on-single-page="value" v-model:current-page="currentPage"
            v-model:page-size="pageSize" :page-sizes="[20, 50, 100]" :total="total"
            @current-change="handleCurrentChange" @size-change="selectchange"
            layout="total, sizes, prev, pager, next, jumper" />
        </div>
      </div>
    </div>
    <el-dialog :title="dialogTitle" v-model="operateVisible" width="50%" destroy-on-close>
      <DynamicForm ref="dynamicForm" :formObj="state.formData" :formItemList="formItemList" labelWidth="150px"
        :rules="state.rules" autoRules>
        <div class="form-item">个人基本信息</div>
        <el-form-item label="姓名" prop="name" required :rules="[{ required: true, message: '请补充姓名' }]">
          <el-select v-model="state.formData.name" filterable placeholder="可直接输入姓名然后选中" @change="handleNameChage">
            <el-option v-for="item in residentList" :key="item.id" :label="item.residentName" :value="item.id" />
          </el-select>
        </el-form-item>
      </DynamicForm>
      <template #footer>
        <span>
          <el-button @click="operateVisible = false">取消</el-button>
          <el-button type="warning" @click="submitPartyManage">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import partyManageApi from '@/api/spb/organizationManage/partyManage'
import partyOrganizationApi from '@/api/spb/organizationManage/partyOrganization'
import globalApi from '@/api/spb/global'
import DynamicForm from '../../components/DynamicForm.vue'
import download from '@/utils/download'
// import PartyImportForm from './PartyImportForm.vue'
import { useRouter } from 'vue-router'
import { dateFormatter2 } from '@/utils/formatTime'
const { push } = useRouter() // 路由
const dynamicForm = ref()
const tree = ref()
const operateVisible = ref(false)
const dialogTitle = ref('')
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const residentList = ref([])
const name = ref('')
const selectList = ref([]) // 表格选中数据
const message = useMessage()
const state = reactive({
  formData: {
    name: ''
  },
  rules: {
    idNumber: [
      { required: true, message: '身份证号不能为空！', trigger: 'blur' },
      {
        pattern:
          /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
        message: '请输入正确的身份证号码',
        trigger: 'blur'
      }
    ],
    name: [{ required: true, message: '姓名不能为空！', trigger: 'change' }],
    telephone: [
      {
        pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    memberType: [{ required: true, message: '党员类型不能为空！', trigger: 'change' }],
    branchId: [{ required: true, message: '所属党支部不能为空！', trigger: 'change' }],
    birthDate: [{ required: true, message: '出生日期不能为空！', trigger: 'blur' }],
    officialMemberTime: [{ required: true, message: '转为正式党员日期不能为空！', trigger: 'blur' }]
  },
  currentNode: {}
})
const treeData = ref()
const defaultProps = {
  children: 'children',
  label: 'name'
}
const sexTypeObj = {
  1: '男',
  2: '女'
}
const optionParty = ref([])
const optionDegree = ref([])
const optionType = ref([])
const optionnation = ref([])
const optionPartyId = ref([])
const loading = ref(true) // 列表加载中
const value = ref(true)
const branchId = ref<any>(undefined)
const formItemList = computed(() => {
  return [
    {
      label: '性别',
      name: 'sex',
      require: false,
      type: 'radioGroup',
      labelFiled: 'name',
      valueFiled: 'id',
      options: [
        {
          id: 1,
          name: '男'
        },
        {
          id: 2,
          name: '女'
        }
      ]
    },
    {
      label: '身份证号',
      name: 'idNumber',
      require: true,
      type: 'input'
    },
    {
      label: '出生日期',
      name: 'birthDate',
      require: true,
      type: 'datePicker'
    },
    {
      label: '民族',
      name: 'nation',
      require: false,
      type: 'select',
      labelFiled: 'name',
      valueFiled: 'id',
      options: optionnation.value
    },
    {
      label: '籍贯',
      name: 'address',
      require: false,
      type: 'cascader',
      change: "placeChange"
    },
    {
      label: '学历',
      name: 'degree',
      require: false,
      type: 'select',
      options: optionDegree.value
    },
    {
      label: '联系电话',
      name: 'telephone',
      require: false,
      type: 'input'
    },
    {
      title: '党员信息',
      type: 'formItem'
    },
    {
      label: '党员类型',
      name: 'memberType',
      require: true,
      type: 'select',
      options: optionType.value
    },
    {
      label: '所属党支部',
      name: 'branchId',
      require: true,
      type: 'treeSelect',
      options: optionParty.value
    },
    {
      label: '党内职务',
      name: 'title',
      require: false,
      type: 'input'
    },
    {
      label: '转为预备党员日期',
      name: 'unofficialMemberTime',
      require: false,
      type: 'datePicker'
    },
    {
      label: '转为正式党员日期',
      name: 'officialMemberTime',
      require: true,
      type: 'datePicker'
    },
    {
      label: '照片',
      name: 'photoUrl',
      require: false,
      type: 'uploadImg'
    },
    {
      label: '住址',
      name: 'homeAddress',
      require: false,
      type: 'textarea'
    }
  ]
})

/** 条数变化 */
const selectchange = (e) => {
  pageSize.value = e
  currentPage.value = 1
  getLeaderManage()
}
/** 页码变化 */
const handleCurrentChange = (e) => {
  currentPage.value = e
  getLeaderManage()
}

const headerCellStyle = computed(() => {
  return { background: '#f0f0f0' }
})

/*自动拆分省市区*/
const splitAddress = (address) => {
  var reg = /.+?(省|市|自治区|自治州|县|区)/g
  return address.match(reg)
}

// 获取居民信息
function getResidentList() {
  globalApi.getResidentList().then((res) => {
    residentList.value = res
  })
}
/** 获取党员学历列表 */
const getDegreeTypeData = () => {
  optionDegree.value = []
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_degree'
  }
  globalApi.getDictData(params).then((res) => {
    res.list.forEach((item) => {
      optionDegree.value.unshift({
        label: item.label,
        value: parseInt(item.value)
      })
    })
  })
}
/** 获取民族类型列表 */
const getnationTypeData = () => {
  optionnation.value = []
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_nation'
  }
  globalApi.getDictData(params).then((res) => {
    res.list.forEach((item) => {
      optionnation.value.unshift({
        label: item.label,
        value: parseInt(item.value)
      })
    })
  })
}
/** 获取党员类型列表 */
const gettypeTypeData = () => {
  optionType.value = []
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_party_member_type'
  }
  globalApi.getDictData(params).then((res) => {
    res.list.forEach((item) => {
      optionType.value.unshift({
        label: item.label,
        value: parseInt(item.value)
      })
    })
  })
}
// 党员类型字段映射
const typeRelate = (item) => {
  let content = ''
  optionType.value.forEach((t) => {
    if (t.value == item) {
      content = t.label
    }
  })
  return content
}

//处理树形数据加value和label
function traverse(nodes) {
  nodes.forEach(node => {
    if (node.id) {
      node.label = node.name;
      node.value = node.id;
    }
    if (node.children && Array.isArray(node.children)) {
      traverse(node.children);
    }
  })
}
// 获取党组织管理列表
function getPartyOrganization() {
  const data = {
    pageNo: 1,
    pageSize: 9999
  }
  partyOrganizationApi.operatePartyOrganization('list', data, null).then((res) => {
    let cloneData = JSON.parse(JSON.stringify(res)) // 对源数据深度克隆
    cloneData = cloneData.filter((father) => {
      // 循环所有项，并添加children属性
      let branchArr = cloneData.filter((child) => father.id == child.parentId) // 返回每一项的子级数组
      branchArr.length > 0 ? (father.children = branchArr) : '' //给父级添加一个children属性，并赋值
      return father.parentId == 0 //返回第一层
    })
    treeData.value = cloneData
    optionParty.value = []
    optionPartyId.value = []
    res.forEach((item) => {
      optionPartyId.value.push({
        label: item.name,
        value: item.id,
      })
    })
    let cloneData2 = JSON.parse(JSON.stringify(cloneData))
    traverse(cloneData2)
    optionParty.value = cloneData2
    nextTick(() => {
      tree.value.setCurrentKey(res[0].id)
      handleNodeClick(res[0])
    })
  })
}

// 获取党员列表
function getLeaderManage() {
  const data = {
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    name: name.value,
    branchId: branchId.value
  }
  partyManageApi.operatePartyManage('page', data, null).then((res) => {
    tableData.value = res.list
    tableData.value.forEach((item) => {
      item.address = splitAddress(item.address)
    })
    total.value = res.total
    if (tableData.value.length === 0) {
      value.value = true
    } else {
      value.value = false
    }
    loading.value = false
  }).catch(error => {
    loading.value = false
  })
}

// 新增/编辑党员
function submitPartyManage() {
  dynamicForm.value.validateForm(() => {
    let data = dynamicForm.value.getFormData()
    optionPartyId.value.forEach((item) => {
      if (item.value == data.branchId) {
        data.belongBranch = item.label
      }
    })
    const params = {
      id: data.id
    }
    data.schedule = data.schedule?.join('、')
    const partyData = {
      name: data.name,
      sex: data.sex,
      idNumber: data.idNumber,
      birthDate: data.birthDate,
      nation: data.nation,
      address: data.address,
      degree: data.degree,
      telephone: data.telephone,
      photoUrl: data.photoUrl,
      homeAddress: data.homeAddress,
      memberType: data.memberType,
      belongBranch: data.belongBranch,
      branchId: data.branchId,
      title: data.title,
      unofficialMemberTime: data.unofficialMemberTime,
      officialMemberTime: data.officialMemberTime,
    }
    if (
      partyData.address[0] != null &&
      partyData.address[1] != null &&
      partyData.address[2] != null
    ) {
      partyData.address = partyData.address[0] + partyData.address[1] + partyData.address[2]
    }
    const type = dialogTitle.value.includes('新增') ? 'create' : 'update'
    if (type == 'update') {
      partyData.id = data.id
    }
    partyManageApi.operatePartyManage(type, partyData, params).then(() => {
      getLeaderManage()
      operateVisible.value = false
      message.success(`${dialogTitle.value}成功`)
    })
  })
}
/** 批量删除 */
const handleSelectionChange = (e) => {
  selectList.value = e
}
const alldelbtn = () => {
  if (selectList.value.length == 0) {
    ElMessage({
      message: '至少选中一条数据！',
      type: 'warning'
    })
    return
  }
  ElMessageBox.confirm(`确认删除选中党员吗？删除当前选中党员会删除当前选中党员对应的领导班子的任职资格，请谨慎操作！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const idList = reactive([])
      selectList.value.forEach((item) => {
        return idList.push(item.id)
      })
      partyManageApi.deletePartyManage(idList).then((res) => {
        if (res === true) {
          ElMessage.success('删除成功！')
          getLeaderManage()
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}
// 删除党员
function delPartyManage(row) {
  const params = {
    id: row.id
  }
  ElMessageBox.confirm(`确认删除党员【${row.name}】吗？删除当前党员会删除其对应的领导班子的任职资格，请谨慎操作！`, '提示', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消'
  }).then(() => {
    partyManageApi.operatePartyManage('delete', null, params).then(() => {
      getLeaderManage()
      operateVisible.value = false
      message.success(`删除${row.name}成功`)
    })
  })
}

/** 下载模版 */
const downloadbtn = () => {
  ElMessageBox.confirm('是否确认下载党员模版?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const data = await partyManageApi.downloadPartyManage()
      download.excel(data, '模板.xls')
      ElMessage({
        type: 'info',
        message: '正在请求资源请稍后',
        duration: 500
      })
      ElMessage.success('下载成功！')
    })
    .catch(() => {
      ElMessage.info('已取消下载')
    })
}

/** 批量导入 */
const importFormRef = ref()
const importbtn = () => {
  importFormRef.value.open()
}

/** 批量导出 */
const exportbtn = () => {
  ElMessageBox.confirm('是否确认批量导出党员?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const queryParams = {
        pageNo: currentPage.value,
        pageSize: pageSize.value,
        name: name.value,
        branchId: branchId.value
      }
      const data = await partyManageApi.exportPartyManage(queryParams)
      download.excel(data, '党员.xls')
      ElMessage({
        type: 'info',
        message: '正在请求资源请稍后',
        duration: 500
      })
      ElMessage.success('下载成功！')
    })
    .catch(() => {
      ElMessage.info('已取消下载')
    })
}
/** 详情 */
const detailsbtn = (row: any) => {
  push({
    name: 'partyDetails',
    query: {
      id: row.id
    }
  })
}
// 节点点击
function handleNodeClick(node) {
  state.currentNode = node
  branchId.value = node.id
  getLeaderManage()
}

// 姓名下拉事件
function handleNameChage(select) {
  const params = {
    id: select
  }
  globalApi.getResidentDetail(params).then((res) => {
    state.formData = res
    state.formData.name = res.residentName
  })
}
// 表格操作
function operateRow(type, row) {
  if (type === 'del') {
    delPartyManage(row)
    return
  }
  state.formData = type === 'add' ? {} : row
  dialogTitle.value = `${type === 'add' ? '新增' : '编辑'}党员`
  operateVisible.value = true
}
// 重置操作
function handleReset() {
  currentPage.value = 1
  pageSize.value = 20
  name.value = ''
  getLeaderManage()
}

onMounted(() => {
  getResidentList()
  getDegreeTypeData()
  getnationTypeData()
  gettypeTypeData()
  getPartyOrganization()
})
</script>

<style lang="scss" scoped>
@import url('../../styles/global.css');

.operate {
  display: flex;
}

.content {
  display: flex;

  .left {
    width: 266px;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    border: 1px solid #efefef;
    margin-right: 16px;
  }

  .right {
    width: calc(100% - 266px);
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

::v-deep .el-dialog__body {
  height: 500px;
  overflow: auto;
}

.btn {
  width: 80px;
  height: 30px;
  line-height: 20px;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}

.btnreset {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(187, 187, 187, 1);
  color: rgba(142, 142, 142, 1);
}

.btnsearch {
  background-color: #cc352f;
  color: rgba(255, 255, 255, 1);
  border: 1px solid #cc352f;
}

.btn:hover {
  opacity: 0.8;
}

.btnhover:hover {
  opacity: 0.8;
}

::v-deep .el-form-item__label {
  font-weight: 500;
}
.namecont {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>